package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.StrategyCommend;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelCommend;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.ITravelCommendService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.domain.DestinationTemplate;
import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.domain.TravelTemplate;
import cn.wolfcode.luowowo.search.domain.UserInfoTemplate;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.*;
import cn.wolfcode.luowowo.search.vo.SearchResult;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class IndexController {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelCommendService travelCommendService;

    @Reference
    private ITravelService travelService;

    @Reference
    private IStrategyCommendService strategyCommendService;

    @Reference
    private IDestinationTemplateSearchService destinationTemplateSearchService;

    @Reference
    private IUserInfoTemplateSearchService userInfoTemplateSearchService;

    @Reference
    private IStrategyTemplateSearchService strategyTemplateSearchService;

    @Reference
    private ITravelTemplateSearchService travelTemplateSearchService;

    @Reference
    private ISearchService searchService;

    //@RequireLogin
    @RequestMapping("")
    public String index(HttpServletRequest req, HttpServletResponse resp,Model model){
        //1.从request对象中获取cookie对象,并解析出token
        /*Cookie[] cookies = req.getCookies();
        String token = "";
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    token = cookie.getValue();
                    //延时
                    cookie.setMaxAge(RedisKeys.USER_LOGIN.getTime().intValue());
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
        }*/
        String token = CookieUtil.getToken(req,resp);
        String userStr = userInfoRedisService.getToken(token);
        UserInfo user = JSON.parseObject(userStr, UserInfo.class);
        req.getSession().setAttribute("userInfo",user);
        //List<TravelComment> list = travelCommentService.listNewsCommends();

        //tcs
        List<TravelCommend> list = travelCommendService.getTop5();
        model.addAttribute("tcs",list);

        //sc
        StrategyCommend strategyCommend = strategyCommendService.getTop5().get(0);
        model.addAttribute("sc",strategyCommend);
        return "/index/index";
    }

    @RequestMapping("/index/travelPage")
    public String travelPage(@ModelAttribute("qo") TravelQuery qo, Model model){
        PageInfo query = travelService.query(qo);
        model.addAttribute("pageInfo",query);
        return "/index/travelPageTpl";
    }

    @RequestMapping("/q")
    public String search(@ModelAttribute("qo") SearchQueryObject qo, Model model){
        switch (qo.getType()){
            case SearchQueryObject.SEARCH_TYPE_DEST:
                return searchDest(model, qo);
            case SearchQueryObject.SEARCH_TYPE_TRAVEL:
                return searchTravel(model, qo);
            case SearchQueryObject.SEARCH_TYPE_STRATEGY:
                return searchStrategy(model, qo);
            case SearchQueryObject.SEARCH_TYPE_USER:
                return searchUser(model, qo);
            default:return searchAll(model, qo);
        }
    }

    //搜索全部
    private String searchAll(Model model, SearchQueryObject qo) {
        Page<UserInfoTemplate> us = searchService.searchWithHighlight(UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName");
        Page<StrategyTemplate> sts = searchService.searchWithHighlight(StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary");
        Page<TravelTemplate> ts = searchService.searchWithHighlight(TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        Page<DestinationTemplate> ds = searchService.searchWithHighlight(DestinationTemplate.INDEX_NAME, DestinationTemplate.TYPE_NAME,
                DestinationTemplate.class, qo, "name", "info");
        SearchResult result = new SearchResult();
        result.setTotal(us.getTotalElements() + sts.getTotalElements() + ts.getTotalElements() + ds.getTotalElements());

        result.setDests(ds.getContent());
        result.setStrategys(sts.getContent());
        result.setTravels(ts.getContent());
        result.setUsers(us.getContent());

        model.addAttribute("data",result);
        return "/index/searchAll";
    }

    //用户
    private String searchUser(Model model, SearchQueryObject qo) {
        Page<UserInfoTemplate> page = searchService.searchWithHighlight(UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickname", "destName");
        model.addAttribute("page",page);
        return "/index/searchUser";
    }

    //攻略
    private String searchStrategy(Model model, SearchQueryObject qo) {
        Page<StrategyTemplate> page = searchService.searchWithHighlight(StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary");
        model.addAttribute("page",page);
        return "/index/searchStrategy";
    }

    //游记
    private String searchTravel(Model model, SearchQueryObject qo) {
        Page<TravelTemplate> page = searchService.searchWithHighlight(TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        model.addAttribute("page",page);
        return "/index/searchTravel";
    }

    //目的地
    private String searchDest(Model model, SearchQueryObject qo) {
        //通过关键字,查询是否存在该目的地
        DestinationTemplate dest = destinationTemplateSearchService.findByDestName(qo.getKeyword());
        //若存在,查询前五 游记,攻略,用户
        if (dest != null){
            SearchResult data = new SearchResult();
            //游记
            List<TravelTemplate> ts = travelTemplateSearchService.findByDestName(qo.getKeyword());
            data.setTotal(ts.size() + data.getTotal());
            if (ts.size() > 5){
                ts = ts.subList(0,5);
            }
            //攻略
            List<StrategyTemplate> sts = strategyTemplateSearchService.findByDestName(qo.getKeyword());
            data.setTotal(ts.size() + data.getTotal());
            if (sts.size() > 5) {
                sts = sts.subList(0,5);
            }
            //用户
            List<UserInfoTemplate> us = userInfoTemplateSearchService.findByDestName(qo.getKeyword());
            data.setTotal(ts.size() + data.getTotal());
            if (us.size() > 5) {
                us = us.subList(0,5);
            }

            data.setUsers(us);
            data.setTravels(ts);
            data.setStrategys(sts);

            model.addAttribute("data",data);
        }
        //若不存在,则提示不存在
        model.addAttribute("dest",dest);
        return "/index/searchDest";
    }
}
